﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MishraReader.Entities.ShareServices
{
    public sealed class ReadItLaterShareService : ShareServiceBase
    {
        private static readonly string AppKey = HttpUtility.UrlEncode("4cFT9Dfug9dt2H0x16dd44fx5bp1C8eP");
        public override bool IsSupported
        {
            get { return true; }
        }
        public ReadItLaterShareService()
        {
            ServiceName = "Read It Later";
            ServiceId = new Guid("435F51F8-C02E-440F-941F-1D107C557D86"); 
            ServiceType = ServiceType.Bookmark;
        }

        public override bool IsWellConfigured(string userName, string password)
        {
            //https://readitlaterlist.com/v2/auth?username=name&password=123&apikey=yourapikey
            var url =
                string.Format("https://readitlaterlist.com/v2/auth?username={0}&password={1}&apikey={2}", HttpUtility.UrlEncode(userName),
                              HttpUtility.UrlEncode(password), AppKey);


            var webClient = new WebClient();
            try
            {
                var response = webClient.UploadString(new Uri(url, UriKind.Absolute), "GET");
            }
            catch (WebException)
            {
                // 200 - Request was successful
                //400 - Invalid request, please make sure you follow the documentation for proper syntax
                //401 - Username and/or password is incorrect
                //403 - Rate limit exceeded, please wait a little bit before resubmitting
                //503 - Read It Later's sync server is down for scheduled maintenance.
                return false;
            }
            return true;
        }

        public override void Share(ShareServiceAccount account, string message, Item item)
        {
            //https://readitlaterlist.com/v2/add?username=name&password=123&apikey=yourapikey&url=http://google.com&title=Google
            var url = string.Format("https://readitlaterlist.com/v2/add?username={0}&password={1}&apikey={2}&url={3}&title={4}",
                                    HttpUtility.UrlEncode(account.UserName), HttpUtility.UrlEncode(account.Password), AppKey,
                                    HttpUtility.UrlEncode(item.PostUri.ToString()), HttpUtility.UrlEncode(item.Title));

            var webClient = new WebClient();
            webClient.UploadString(new Uri(url, UriKind.Absolute), "GET");
        }
    }
}